import 'package:flutter/material.dart';
import 'package:flutter2/colors.dart';
import 'package:flutter2/http/api.dart';
import 'package:flutter2/http/dio_manager.dart';
import 'package:flutter2/item/item_repay.dart';
import 'package:flutter2/model/order_entity.dart';
import 'package:flutter2/model/pay_channel_entity.dart';
import 'package:flutter2/model/pay_url_entity.dart';
import 'package:flutter2/model/repay_entity.dart';
import 'package:flutter2/ui/sheet.dart';
import 'package:flutter2/ui/web.dart';
import 'package:flutter2/utils/num.dart';
import 'package:flutter2/widget/base/base_container.dart';
import 'package:flutter2/widget/base/normal_button.dart';
import 'package:flutter2/widget/base/normal_text.dart';
import 'package:flutter2/widget/info_view.dart';
import 'package:flutter2/widget/title_bar.dart';
import 'package:get/get.dart';

class RepayPage extends StatefulWidget {
  const RepayPage({super.key, required this.order});

  final OrderEntity order;

  @override
  State<RepayPage> createState() => _RepayPageState();
}

class _RepayPageState extends State<RepayPage> {
  bool init = false;

  final List<RepayPlanEntity> _plans = [];
  int repay = 0;
  int curDur = 1;

  @override
  void initState() {
    super.initState();
    var param = getParams();
    param["tube"] = "03";
    param["correspondacquiregrass"] = widget.order.orderId;
    DioManager.request<RepayEntity>(
      path: HttpApi.repayDetailI,
      data: param,
      onSuccess: (data) {
        if (data == null) return;
        init = true;
        _plans.addAll(data.plans);
        repay = _plans.firstOrNull?.repay ?? 0;
        curDur = _plans.firstOrNull?.cur ?? 1;
        setState(() {});
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TitleBar.buildAppBar(title: "还款详情"),
      body: Column(
        children: [
          if (init) ...[
            Expanded(
              child: SingleChildScrollView(
                physics: BouncingScrollPhysics(),
                child: Column(
                  children: [
                    BaseContainer(
                      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                      margin: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                      width: double.infinity,
                      radius: 10,
                      background: Colors.white,
                      child: Column(
                        children: [
                          NormalText(
                            text: "Monto a pagar",
                            fontColor: btnColor,
                          ),
                          SizedBox(height: 10),
                          NormalText(
                            text: widget.order.loanAmount.formatAmount(),
                            fontColor: mainText,
                            fontSize: 50,
                          ),
                          SizedBox(height: 10),
                          InfoView(
                            leftText: "Fecha préstamo",
                            rightText: widget.order.loanTime,
                          ),
                        ],
                      ),
                    ),
                    ...getPlans(),
                  ],
                ),
              ),
            ),
            getBottom(),
          ],
        ],
      ),
    );
  }

  var expand = <int, bool>{};

  List<Widget> getPlans() {
    return _plans.map((e) {
      return ItemRepay(
        expandClick: () {
          expand[e.cur] = !(expand[e.cur] ?? false);
          setState(() {});
        },
        expand: expand[e.cur],
        totalPeriod: widget.order.period,
        repayPlan: e,
        check: e.cur <= curDur,
        click: () {
          curDur = e.cur;
          setState(() {});
        },
      );
    }).toList();
  }

  int getTotal() {
    int total = 0;
    for (var element in _plans) {
      if (element.cur <= curDur && unComplete(element)) {
        total += element.repay;
      }
    }
    return total;
  }

  Widget getBottom() {
    if (widget.order.period == 1) {
      return SafeArea(
        bottom: true,
        top: false,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
          child: Row(
            children: [
              if (widget.order.extend == "1") ...[
                Expanded(
                  child: NormalButton(
                    background: Colors.transparent,
                    text: "Prórroga",
                    fontColor: btnColor,
                  ),
                ),
                SizedBox(
                  width: 10,
                ),
              ],
              Expanded(
                child: NormalButton(
                  text: "Pagar",
                  click: () => getChannels(),
                ),
              ),
            ],
          ),
        ),
      );
    } else {
      return SafeArea(
        child: BaseContainer(
          width: double.infinity,
          radius: 10,
          background: Colors.white,
          margin: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
          padding: EdgeInsets.all(16),
          child: Row(
            children: [
              Expanded(
                child: NormalText(
                  fontSize: 30,
                  fontColor: mainText,
                  text: getTotal().formatAmount(),
                ),
              ),
              NormalButton(
                enable: curDur > 0,
                text: "Pagar",
                click: () => getChannels(),
              )
            ],
          ),
        ),
      );
    }
  }

  List<PayChannelEntity> channels = [];

  getChannels() {
    if (channels.isNotEmpty) {
      pay();
      return;
    }
    DioManager.request<List<PayChannelEntity>>(
      path: HttpApi.getPayChannels,
      onSuccess: (data) {
        channels.clear();
        channels.addAll(data ?? []);
        pay();
      },
    );
  }

  pay() {
    if (channels.isEmpty) return;
    SheetData.showSheetItems<PayChannelEntity>(
      data: channels,
      call: (item) {
        var param = getParams();
        param["tube"] = "03";
        param["whenclever"] = item.getName();
        param["correspondacquiregrass"] = widget.order.orderId;
        List<String> list = [];
        for (var element in _plans) {
          if (element.cur <= curDur && unComplete(element)) {
            list.add(element.id.toString());
          }
        }
        param["sobdeadlinefreeway"] = list.join(",");
        DioManager.request<PayUrlEntity>(
          path: HttpApi.getPayInfo,
          data: param,
          onSuccess: (data) {
            Get.to(WebPage(
              url: data?.url,
              title: "还款",
            ));
          },
        );
      },
    );
  }
}

bool unComplete(RepayPlanEntity repayPlan) {
  return repayPlan.status == 0 || repayPlan.status == 4 || repayPlan.status == 5;
}
